
package com.java.controller.admin;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Pattern.Flag;

import org.hibernate.validator.internal.metadata.facets.Validatable;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.java.entity.Good;
import com.java.entity.Image;
import com.java.entity.User;
import com.java.mapper.GoodMapper;
import com.java.service.impl.GoodServiceImpl;
import com.java.service.impl.ImageServiceImpl;
import com.java.service.impl.UserServiceImpl;


/**
* @author Kidney
* 鍒涘缓鏃堕棿锛�2019骞�2鏈�17鏃� 涓嬪崍4:32:24
* Description:
*/
/**
 * @author KIDNEY
 *
 */

@Controller
@RequestMapping("/good/")
public class GoodController {

	@Autowired
	private GoodServiceImpl gsl;

	@Autowired
	private ImageServiceImpl isl;

	@Autowired
	private UserServiceImpl us;

	
	
	
	
	
	
	

	@RequestMapping("update_select_byid")
	@ResponseBody
	public ModelAndView updateGood(String goodName, String goodBrand, String goodColour, String goodDesc, Float goodPrice,
			Integer goodLimitRent, String goodSize, Float deposit, Integer goodId ,Float goodDepositNeed) {
		ModelAndView mav = new ModelAndView();
		Good good = new Good();
		good.setGoodBrand(goodBrand);
		good.setGoodColour(goodColour);
		good.setGoodName(goodName);
		good.setGoodDepositNeed(deposit);
		good.setGoodSize(goodSize);
		good.setGoodDesc(goodDesc);
		good.setGoodPrice(goodPrice);
		if (goodPrice!=null) {
			good.setGoodPriceWeek((float) (goodPrice*0.05));
		}
		good.setGoodId(goodId);
		good.setGoodLimitRent(goodLimitRent);
		good.setGoodDepositNeed(goodDepositNeed);
		int flag = gsl.updateByPrimaryKeySelective(good);

		if (flag == 0) {
			mav.getModel().put("status", "淇敼澶辫触");
		} else {
			mav.getModel().put("status", "淇敼鎴愬姛");
		}
		
		int pageSize = 10;
		
		List<Good> list = gsl.getPaged(pageSize, 1);
		mav.getModel().put("list", list);
		int count = gsl.count();
		// 璁＄畻涓�鍏辨湁澶氬皯椤�
		int pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
		
	
		mav.getModel().put("pageCount", pageCount);
		mav.getModel().put("pageNum", 1);
		
		mav.setViewName("/pages/admin/good_update_delete_insert.jsp");
		return mav;
	}

	// ----------鏌ヨ------------

	// 寰楀埌鎸囧畾鍟嗗搧淇℃伅 KEY= BARND KEY= NAME KEY=COLOUR
	@RequestMapping("good_select_conditon")
	@ResponseBody
	public ModelAndView selectByConditionGood(String brand, String name, String colour) {
		
		int pageSize = 10;
		ModelAndView mav = new ModelAndView();
		
		Good good = new Good();
		good.setGoodBrand(brand);
		good.setGoodColour(colour);
		good.setGoodName(name);
		List<Good> list =gsl.selectByCondition(good);
		
		mav.getModel().put("list", list);

		int count = gsl.count();
		// 璁＄畻涓�鍏辨湁澶氬皯椤�

		int pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;

		mav.getModel().put("pageCount", pageCount);

		mav.getModel().put("pageNum", 1);
		mav.setViewName("/pages/front/shop.jsp");
		
		return mav;
	}

	// 寰楀埌鎸囧畾鍟嗗搧淇℃伅 KEY=ID
	@RequestMapping("good_select_byid")
	@ResponseBody
	public Good selectByPrimaryKeyGood(Integer id) {
		return gsl.selectByPrimaryKey(id);
	}

	// 寰楀埌鎸囧畾鍟嗗搧鎵�鏈夊浘鐗� KEY=GOOD_ID
	@RequestMapping("image_select_byid")
	@ResponseBody
	public List<Image> selectByPrimaryKeyImage(Integer id) {
		return isl.selectByGoodId(id);
	}


	@RequestMapping("good_insert")
	@ResponseBody
	public ModelAndView insertGood(String goodName, String goodBrand, String goodColour, String goodDesc, Float goodPrice,
			Integer goodLimitRent, String goodSize, Float goodDepositNeed) {
		ModelAndView mav = new ModelAndView();
		Good good = new Good();
		good.setGoodBrand(goodBrand);
		good.setGoodColour(goodColour);
		good.setGoodName(goodName);
		good.setGoodDepositNeed(goodDepositNeed);
		good.setGoodSize(goodSize);
		good.setGoodDesc(goodDesc);
		good.setGoodPrice(goodPrice);
		if (goodPrice!=null) {
			good.setGoodPriceWeek((float) (goodPrice*0.05));
		}
		
		good.setGoodLimitRent(goodLimitRent);
		int flag = gsl.insertSelective(good);

		if (flag == 0) {
			mav.getModel().put("status", "鎻掑叆閿欒");
		} else {

			mav.getModel().put("status", "鎻掑叆鎴愬姛");
		}
		
		int pageSize = 10;
		
		List<Good> list = gsl.getPaged(pageSize, 1);
		mav.getModel().put("list", list);
		int count = gsl.count();
		// 璁＄畻涓�鍏辨湁澶氬皯椤�
		int pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
		
	
		mav.getModel().put("pageCount", pageCount);
		mav.getModel().put("pageNum", 1);
		
		mav.setViewName("/pages/admin/good_update_delete_insert.jsp");
		return mav;
	}


	@RequestMapping("image_insert")
	@ResponseBody
	public ModelAndView insertImage(Integer goodId, HttpServletRequest request, MultipartRequest files)
			throws IllegalStateException, IOException {

		ModelAndView mav = new ModelAndView();
		mav.setViewName("/pages/admin/good_details.jsp");
		Image im = new Image();
		int flag = 0;
		Map<String, MultipartFile> filesMap = files.getFileMap();
		
		Set<String> keyset = filesMap.keySet();
		for (String key : keyset) {
			MultipartFile file = files.getFile(key);
			String originalFilename = file.getOriginalFilename();
			String uuid = UUID.randomUUID().toString();

			String path = request.getServletContext().getRealPath("/upload");

			String basePath = path.split("webapps")[0] + "webapps\\upload";
			// System.out.println(basePath);
			
			File fileUpload = new File(basePath);
            if (!fileUpload.exists()) {
                fileUpload.mkdir();
            }
			
        
			String filePath = basePath + "\\" + uuid + originalFilename;
			System.out.println(filePath);
			file.transferTo(new File(filePath));
			System.out.println(
					);
		
			String newPath =filePath.replaceAll("\\\\","/");
			
			//String urlPath = "/huahua/resources/upload/"+ uuid + originalFilename;
			String urlPath = "file://"+newPath;
			
			String fileName = uuid + originalFilename;
			
			String url = "/upload/"+fileName;
			
			im.setGoodId(goodId);
			im.setImageUrl(url);
			flag = isl.insert(im);
			
			if (flag == 0) {
				mav.getModel().put("status", "鍥剧墖娣诲姞閿欒");
			} else {
				mav.getModel().put("status", "鍥剧墖娣诲姞鎴愬姛");
			}
			}
		
			Good good = new Good();
			good = selectByPrimaryKeyGood(goodId);
			List<Image> images = isl.selectByGoodId(goodId);
			mav.getModel().put("good", good);
			mav.getModel().put("images", images);
		return mav;
	}

	// ----------鍒犻櫎------------

	// 鍒犻櫎鍟嗗搧 KEY = ID
	@RequestMapping("good_delete")
	@ResponseBody
	public ModelAndView deleteGood(Integer goodId) {
		ModelAndView mav = new ModelAndView();
		int flag = gsl.deleteByPrimaryKey(goodId);
		
		int pageSize = 10;
		
		List<Good> list = gsl.getPaged(pageSize, 1);
		mav.getModel().put("list", list);
		int count = gsl.count();
		// 璁＄畻涓�鍏辨湁澶氬皯椤�
		int pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
		

		mav.getModel().put("pageCount", pageCount);
		mav.getModel().put("pageNum", 1);

		mav.setViewName("/pages/admin/good_update_delete_insert.jsp");
		if (flag == 0) {
			mav.getModel().put("status", "鍒犻櫎閿欒");
		} else {
			mav.getModel().put("status", "鍒犻櫎鐢ㄦ埛" + goodId + "鎴愬姛");
		}
			
		return mav;
	}

	// 鍒犻櫎鎵�鏈夊浘鐗� 鎸囧畾鍟嗗搧
	// @RequestMapping("image_delete")
	// @ResponseBody
	// public int deleteImage(Integer goodId) {
	// int flag = 0;
	// List<Image> images = isl.selectByGoodId(goodId);
	//
	// for (Image i : images) {
	// int imageId = i.getImageId();
	// flag = isl.deleteByPrimaryKey(imageId);
	// }
	// return flag;
	// }


	@RequestMapping("getPaged")
	public ModelAndView getAll(@RequestParam(defaultValue = "1") int pageNum, HttpServletRequest request) {

		Cookie[] cookies = request.getCookies();

		String username = "Please Login";

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("username")) {
				username = "Welcome! " + cookie.getValue();

			}
		}

		int pageSize = 9;
		ModelAndView mav = new ModelAndView();

		List<Good> list = gsl.getPaged(pageSize, pageNum);

		for (int i = 0; i < list.size(); i++) {
			Good g = list.get(i);

			List<Image> ilist = isl.selectByGoodId(g.getGoodId());
			if (ilist.isEmpty()) {
				Good newGood = gsl.selectByPrimaryKey(g.getGoodId());
				newGood.setGoodLike("/huahua/resources/images/error.gif");
				gsl.updateByPrimaryKeySelective(newGood);
			}

			if (!ilist.isEmpty()) {
				Good newGood = gsl.selectByPrimaryKey(g.getGoodId());
				Image newImage = ilist.get(0);
				newGood.setGoodLike(newImage.getImageUrl());
				gsl.updateByPrimaryKeySelective(newGood);
			}

		}

		

		mav.getModel().put("list", list);
		int count = gsl.count();
		int pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
		mav.getModel().put("pageCount", pageCount);
		mav.getModel().put("username", username);
		mav.getModel().put("pageNum", pageNum);
		mav.setViewName("/pages/front/shop.jsp");
		return mav;
	}
	
	
	
	
	
	
	
	@RequestMapping("addToCart")
	public ModelAndView addToCart(Integer id, HttpSession session) {
		@SuppressWarnings("unchecked")
		
		Map<Good, Integer> cart = (Map<Good, Integer>) session.getAttribute("cart");


		ModelAndView mav = new ModelAndView();

		Good good = new Good();
		if (cart == null) {
			cart = new HashMap<>();// 
			good = gsl.selectByPrimaryKey(id);//
			cart.put(good, 1);//
			session.setAttribute("cart", cart);// 
		} else {
			Integer n = cart.get(good);
			if (n == null) {
				good = gsl.selectByPrimaryKey(id);// 
				cart.put(good, 1);

			} else {
				cart.put(good, 1);
			}
		}
		mav.setViewName("/pages/front/trolley.jsp");
		mav.getModel().put("cart", cart);

		float sum = 0;
		float rate = (float) 0.05;
		for (Good key : cart.keySet()) {
			float days = cart.get(key);
			System.out.println(days);
			sum = key.getGoodPrice() * rate * 7 + sum;
			
		}
		mav.getModel().put("sum", sum);
		
		return mav;
	}

	@RequestMapping("cart")
	public ModelAndView getCart(Integer id, HttpSession session) {
		@SuppressWarnings("unchecked")
		Map<Good, Integer> cart = (Map<Good, Integer>) session.getAttribute("cart");
		ModelAndView mav = new ModelAndView();


		mav.setViewName("/pages/front/trolley.jsp");
		mav.getModel().put("cart", cart);

		float sum = 0;
		float rate = (float) 0.05;
		
		if(cart!=null){
		for (Good key : cart.keySet()) {
			float days =cart.get(key);
			System.out.println(days);
			sum = key.getGoodPrice() * rate *days + sum;
		}
		mav.getModel().put("sum", sum);
		}
		
		return mav;
	}

	@RequestMapping("test")
	@ResponseBody
	public Map<Good, Integer> test(HttpSession session) {
		
		Map<Good, Integer> cart = (Map<Good, Integer>) session.getAttribute("cart");
		return cart;
	}
	
	

	
	
	@RequestMapping("deleteToCart")
	public ModelAndView deleteToCart(HttpSession session) {

		ModelAndView mav = new ModelAndView();
		Map<Good, Integer> cart = null;

		mav.getModel().put("cart", cart);
		session.removeAttribute("cart");
		mav.setViewName("/pages/front/trolley.jsp");
		return mav;
	}

	@RequestMapping("getGoodDetails")
	public ModelAndView getGoodDetails(HttpSession session, int id) {

		ModelAndView mav = new ModelAndView();
		mav.setViewName("/pages/front/good_details.jsp");

		Good good = new Good();
		good = selectByPrimaryKeyGood(id);
		List<Image> images = isl.selectByGoodId(id);
		mav.getModel().put("good", good);
		mav.getModel().put("images", images);
		return mav;
	}

}
